#include "board_uart.h"
#include "board_config.h"
#include "platform.h"
#include "ring_buffer.h"
#include "sbus.h"
#include <stdio.h>

#define TX_BUF_LEN 256

#if BOARD_UARTn > 0
UART_HandleTypeDef uart1handler;
ring_buffer uart1_tx_rb;
uint8_t uart1_tx_buf[TX_BUF_LEN];
uint8_t uart1_tx_dma[TX_BUF_LEN];
#if BOARD_UARTn > 1
UART_HandleTypeDef uart2handler;
ring_buffer uart2_tx_rb;
uint8_t uart2_tx_buf[TX_BUF_LEN];
uint8_t uart2_tx_dma[TX_BUF_LEN];
#endif
#endif

#ifdef BOARD_SBUS_UART
#define RC_FRAME_LEN	25
#elif defined(BOARD_DSM2_UART)
#define RC_FRAME_LEN	16
#endif

#if defined(BOARD_SBUS_UART) || defined(BOARD_DSM2_UART)
uint8_t rc_dma_buf[RC_FRAME_LEN] = {0};
uint16_t rc_channels[18]={0};
#endif

void board_uart_init(UART_HandleTypeDef *uarthandler, uint32_t baudrate)
{
#if BOARD_UARTn > 0
	if (uarthandler == &uart1handler) {
		uart1handler.Instance          = BOARD_UART1;

		uart1handler.Init.BaudRate     = baudrate;
		uart1handler.Init.WordLength   = UART_WORDLENGTH_8B;
		uart1handler.Init.StopBits     = UART_STOPBITS_1;
		uart1handler.Init.Parity       = UART_PARITY_NONE;
		uart1handler.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
		uart1handler.Init.Mode         = UART_MODE_TX_RX;
		uart1handler.Init.OverSampling = UART_OVERSAMPLING_16;

		HAL_UART_Init(&uart1handler);
#if (BOARD_SBUS_UART == 1) || (BOARD_DSM2_UART == 1)
		HAL_UART_Receive_DMA(&uart1handler, rc_dma_buf, RC_FRAME_LEN);
#endif
		rb_init(&uart1_tx_rb, TX_BUF_LEN, uart1_tx_buf, ELEMENT_TYPE_U8);
	}
#endif
#if BOARD_UARTn > 1
	else if (uarthandler == &uart2handler) {
		uart2handler.Instance          = BOARD_UART2;

		uart2handler.Init.BaudRate     = baudrate;
		uart2handler.Init.WordLength   = UART_WORDLENGTH_8B;
		uart2handler.Init.StopBits     = UART_STOPBITS_1;
		uart2handler.Init.Parity       = UART_PARITY_NONE;
		uart2handler.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
		uart2handler.Init.Mode         = UART_MODE_TX_RX;
		uart2handler.Init.OverSampling = UART_OVERSAMPLING_16;

		HAL_UART_Init(&uart2handler);
#if (BOARD_SBUS_UART == 2) || (BOARD_DSM2_UART == 2)
		HAL_UART_Receive_DMA(&uart2handler, rc_dma_buf, RC_FRAME_LEN);
#endif
		rb_init(&uart2_tx_rb, TX_BUF_LEN, uart2_tx_buf, ELEMENT_TYPE_U8);
	}
#endif
#ifdef BOARD_STDOUT_UART
	setbuf(stdout, NULL);
#endif
}

void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
#if BOARD_UARTn > 0
	static DMA_HandleTypeDef u1_hdma_tx;
	static DMA_HandleTypeDef u1_hdma_rx;
#endif
#if BOARD_UARTn > 1
	static DMA_HandleTypeDef u2_hdma_tx;
	static DMA_HandleTypeDef u2_hdma_rx;
#endif
	GPIO_InitTypeDef  GPIO_InitStruct;

#if BOARD_UARTn > 0
	if (huart == &uart1handler) {
		/*##-1- Enable peripherals and GPIO Clocks #################################*/
		/* Enable GPIO TX/RX clock */
		BOARD_UART1_TX_GPIO_CLK_ENABLE();
		BOARD_UART1_RX_GPIO_CLK_ENABLE();
		/* Enable USART2 clock */
		BOARD_UART1_CLK_ENABLE();
		/* Enable DMA1 clock */
		BOARD_UART1_DMA_CLK_ENABLE();

		/*##-2- Configure peripheral GPIO ##########################################*/
		/* UART TX GPIO pin configuration  */
		GPIO_InitStruct.Pin       = BOARD_UART1_TX_PIN;
		GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
		GPIO_InitStruct.Pull      = GPIO_NOPULL;
		GPIO_InitStruct.Speed     = GPIO_SPEED_FAST;
		GPIO_InitStruct.Alternate = BOARD_UART1_TX_AF;

		HAL_GPIO_Init(BOARD_UART1_TX_GPIO_PORT, &GPIO_InitStruct);

		/* UART RX GPIO pin configuration  */
		GPIO_InitStruct.Pin = BOARD_UART1_RX_PIN;
		GPIO_InitStruct.Alternate = BOARD_UART1_RX_AF;

		HAL_GPIO_Init(BOARD_UART1_RX_GPIO_PORT, &GPIO_InitStruct);

		/*-3- Configure the DMA streams */
		/* Configure the DMA handler for Transmission process */
		u1_hdma_tx.Instance                 = BOARD_UART1_TX_DMA_STREAM;
		u1_hdma_tx.Init.Channel             = BOARD_UART1_TX_DMA_CHANNEL;
		u1_hdma_tx.Init.Direction           = DMA_MEMORY_TO_PERIPH;
		u1_hdma_tx.Init.PeriphInc           = DMA_PINC_DISABLE;
		u1_hdma_tx.Init.MemInc              = DMA_MINC_ENABLE;
		u1_hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		u1_hdma_tx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		u1_hdma_tx.Init.Mode                = DMA_NORMAL;
		u1_hdma_tx.Init.Priority            = DMA_PRIORITY_LOW;
		u1_hdma_tx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
		u1_hdma_tx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		u1_hdma_tx.Init.MemBurst            = DMA_MBURST_INC4;
		u1_hdma_tx.Init.PeriphBurst         = DMA_PBURST_INC4;

		HAL_DMA_Init(&u1_hdma_tx);

		/* Associate the initialized DMA handle to the the UART handle */
		__HAL_LINKDMA(huart, hdmatx, u1_hdma_tx);

		/* Configure the DMA handler for Receiving process */
		u1_hdma_rx.Instance                 = BOARD_UART1_RX_DMA_STREAM;
		u1_hdma_rx.Init.Channel             = BOARD_UART1_RX_DMA_CHANNEL;
		u1_hdma_rx.Init.Direction           = DMA_PERIPH_TO_MEMORY;
		u1_hdma_rx.Init.PeriphInc           = DMA_PINC_DISABLE;
		u1_hdma_rx.Init.MemInc              = DMA_MINC_ENABLE;
		u1_hdma_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		u1_hdma_rx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		u1_hdma_rx.Init.Mode                = DMA_NORMAL;
		u1_hdma_rx.Init.Priority            = DMA_PRIORITY_HIGH;
		u1_hdma_rx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
		u1_hdma_rx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		u1_hdma_rx.Init.MemBurst            = DMA_MBURST_INC4;
		u1_hdma_rx.Init.PeriphBurst         = DMA_PBURST_INC4;

		HAL_DMA_Init(&u1_hdma_rx);
		__HAL_LINKDMA(huart, hdmarx, u1_hdma_rx);
		/*##-4- Configure the NVIC for DMA #########################################*/

		HAL_NVIC_SetPriority(BOARD_UART1_DMA_RX_IRQn, 3, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART1_DMA_RX_IRQn);

		/* NVIC configuration for DMA transfer complete interrupt (USARTx_TX) */
		HAL_NVIC_SetPriority(BOARD_UART1_DMA_TX_IRQn, 4, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART1_DMA_TX_IRQn);

		/* NVIC configuration for USART TC interrupt */
		HAL_NVIC_SetPriority(BOARD_UART1_IRQn, 3, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART1_IRQn);
	}
#endif
#if BOARD_UARTn > 1
	else if (huart == &uart2handler) {
		/*-1- Enable peripherals and GPIO Clocks */
		/* Enable GPIO TX/RX clock */
		BOARD_UART2_TX_GPIO_CLK_ENABLE();
		BOARD_UART2_RX_GPIO_CLK_ENABLE();
		/* Enable USART1 clock */
		BOARD_UART2_CLK_ENABLE();
		/* Enable DMA2 clock */
		BOARD_UART2_DMA_CLK_ENABLE();

		/*-2- Configure peripheral GPIO */
		/* UART TX GPIO pin configuration  */
		GPIO_InitStruct.Pin       = BOARD_UART2_TX_PIN;
		GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
		GPIO_InitStruct.Pull      = GPIO_NOPULL;
		GPIO_InitStruct.Speed     = GPIO_SPEED_FAST;
		GPIO_InitStruct.Alternate = BOARD_UART2_TX_AF;

		HAL_GPIO_Init(BOARD_UART2_TX_GPIO_PORT, &GPIO_InitStruct);

		/* UART RX GPIO pin configuration  */
		GPIO_InitStruct.Pin = BOARD_UART2_RX_PIN;
		GPIO_InitStruct.Alternate = BOARD_UART2_RX_AF;

		HAL_GPIO_Init(BOARD_UART2_RX_GPIO_PORT, &GPIO_InitStruct);

		/*-3- Configure the DMA streams */
		/* Configure the DMA handler for Transmission process */
		u2_hdma_tx.Instance                 = BOARD_UART2_TX_DMA_STREAM;
		u2_hdma_tx.Init.Channel             = BOARD_UART2_TX_DMA_CHANNEL;
		u2_hdma_tx.Init.Direction           = DMA_MEMORY_TO_PERIPH;
		u2_hdma_tx.Init.PeriphInc           = DMA_PINC_DISABLE;
		u2_hdma_tx.Init.MemInc              = DMA_MINC_ENABLE;
		u2_hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		u2_hdma_tx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		u2_hdma_tx.Init.Mode                = DMA_NORMAL;
		u2_hdma_tx.Init.Priority            = DMA_PRIORITY_LOW;
		u2_hdma_tx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
		u2_hdma_tx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		u2_hdma_tx.Init.MemBurst            = DMA_MBURST_INC4;
		u2_hdma_tx.Init.PeriphBurst         = DMA_PBURST_INC4;

		HAL_DMA_Init(&u2_hdma_tx);

		/* Associate the initialized DMA handle to the the UART handle */
		__HAL_LINKDMA(huart, hdmatx, u2_hdma_tx);

		/* Configure the DMA handler for Receiving process */
		u2_hdma_rx.Instance                 = BOARD_UART2_RX_DMA_STREAM;
		u2_hdma_rx.Init.Channel             = BOARD_UART2_RX_DMA_CHANNEL;
		u2_hdma_rx.Init.Direction           = DMA_PERIPH_TO_MEMORY;
		u2_hdma_rx.Init.PeriphInc           = DMA_PINC_DISABLE;
		u2_hdma_rx.Init.MemInc              = DMA_MINC_ENABLE;
		u2_hdma_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
		u2_hdma_rx.Init.MemDataAlignment    = DMA_MDATAALIGN_BYTE;
		u2_hdma_rx.Init.Mode                = DMA_NORMAL;
		u2_hdma_rx.Init.Priority            = DMA_PRIORITY_HIGH;
		u2_hdma_rx.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
		u2_hdma_rx.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
		u2_hdma_rx.Init.MemBurst            = DMA_MBURST_INC4;
		u2_hdma_rx.Init.PeriphBurst         = DMA_PBURST_INC4;

		HAL_DMA_Init(&u2_hdma_rx);
		__HAL_LINKDMA(huart, hdmarx, u2_hdma_rx);

		HAL_NVIC_SetPriority(BOARD_UART2_DMA_RX_IRQn, 1, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART2_DMA_RX_IRQn);

		HAL_NVIC_SetPriority(BOARD_UART2_DMA_TX_IRQn, 7, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART2_DMA_TX_IRQn);

		/* NVIC configuration for USART TC interrupt */
		HAL_NVIC_SetPriority(BOARD_UART2_IRQn, 1, 0);
		HAL_NVIC_EnableIRQ(BOARD_UART2_IRQn);
	}
#endif
}

void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)
{
#if BOARD_UARTn > 0
	static DMA_HandleTypeDef u1_hdma_tx;
	static DMA_HandleTypeDef u1_hdma_rx;
#endif
#if BOARD_UARTn > 1
	static DMA_HandleTypeDef u2_hdma_tx;
	static DMA_HandleTypeDef u2_hdma_rx;
#endif

#if BOARD_UARTn > 0
	if (huart == &uart1handler) {
		__HAL_LINKDMA(huart, hdmatx, u1_hdma_tx);
		__HAL_LINKDMA(huart, hdmarx, u1_hdma_rx);

		/*##-1- Reset peripherals ##################################################*/
		BOARD_UART1_FORCE_RESET();
		BOARD_UART1_RELEASE_RESET();

		/*-2- Disable peripherals and GPIO Clocks */
		/* Configure UART Tx as alternate function  */
		HAL_GPIO_DeInit(BOARD_UART1_TX_GPIO_PORT, BOARD_UART1_TX_PIN);
		/* Configure UART Rx as alternate function  */
		HAL_GPIO_DeInit(BOARD_UART1_RX_GPIO_PORT, BOARD_UART1_RX_PIN);

		/*-3- Disable the DMA Streams */
		/* De-Initialize the DMA Stream associate to transmission process */
		HAL_DMA_DeInit(&u1_hdma_tx);
		/* De-Initialize the DMA Stream associate to reception process */
		HAL_DMA_DeInit(&u1_hdma_rx);

		/*-4- Disable the NVIC for DMA */
		HAL_NVIC_DisableIRQ(BOARD_UART1_DMA_TX_IRQn);
		HAL_NVIC_DisableIRQ(BOARD_UART1_DMA_RX_IRQn);
	}
#endif
#if BOARD_UARTn > 1
	else if (huart == &uart2handler) {
		__HAL_LINKDMA(huart, hdmatx, u2_hdma_tx);
		__HAL_LINKDMA(huart, hdmarx, u2_hdma_rx);

		/*-1- Reset peripherals */
		BOARD_UART2_FORCE_RESET();
		BOARD_UART2_RELEASE_RESET();

		/*-2- Disable peripherals and GPIO Clocks */
		/* Configure UART Tx as alternate function  */
		HAL_GPIO_DeInit(BOARD_UART2_TX_GPIO_PORT, BOARD_UART2_TX_PIN);
		/* Configure UART Rx as alternate function  */
		HAL_GPIO_DeInit(BOARD_UART2_RX_GPIO_PORT, BOARD_UART2_RX_PIN);

		/*-3- Disable the DMA Streams */
		/* De-Initialize the DMA Stream associate to transmission process */
		HAL_DMA_DeInit(&u2_hdma_tx);
		/* De-Initialize the DMA Stream associate to reception process */
		HAL_DMA_DeInit(&u2_hdma_rx);

		/*-4- Disable the NVIC for DMA */
		HAL_NVIC_DisableIRQ(BOARD_UART2_DMA_TX_IRQn);
		HAL_NVIC_DisableIRQ(BOARD_UART2_DMA_RX_IRQn);
	}
#endif
}

uint16_t board_uart_send(uint8_t dev_num, uint8_t* tx_buf, uint16_t size)
{
	uint16_t len = 0;
#if BOARD_UARTn > 0
	if (dev_num == 0) {
		for (len = 0; len < size; len++) {
			if (!rb_insert(&uart1_tx_rb, (void *)(&tx_buf[len])))
				break;
		}
		uint32_t tmp = uart1handler.State;
		if ((tmp == HAL_UART_STATE_READY)
		    || (tmp == HAL_UART_STATE_BUSY_RX)) {
			HAL_UART_TxCpltCallback(&uart1handler);
		}
	}
#endif
#if BOARD_UARTn > 1
	else if (dev_num == 1) {
		for (len = 0; len < size; len++) {
			if (!rb_insert(&uart2_tx_rb, (void *)(&tx_buf[len])))
				break;
		}
		uint32_t tmp = uart2handler.State;
		if ((tmp == HAL_UART_STATE_READY)
		    || (tmp == HAL_UART_STATE_BUSY_RX)) {
			HAL_UART_TxCpltCallback(&uart2handler);
		}
	}
#endif
	return len;
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef* uarthandler)
{
#if BOARD_UARTn > 0
	if (uarthandler == &uart1handler) {
		uint16_t num = 0;
		while(!rb_is_empty(&uart1_tx_rb)) {
			rb_remove(&uart1_tx_rb, (void *)(&uart1_tx_dma[num++]));
			if (num == TX_BUF_LEN) {
				break;
			}
		}
		if (num > 0) {
			HAL_UART_Transmit_DMA(&uart1handler,
					      uart1_tx_dma,
					      num);
		}
	}
#endif
#if BOARD_UARTn > 1
	else if (uarthandler == &uart2handler) {
		uint16_t num = 0;
		while(!rb_is_empty(&uart2_tx_rb)) {
			rb_remove(&uart2_tx_rb, (void *)(&uart2_tx_dma[num++]));
			if (num == TX_BUF_LEN) {
				break;
			}
		}
		if (num > 0) {
			HAL_UART_Transmit_DMA(&uart2handler,
					      uart2_tx_dma,
					      num);
		}
	}
#endif
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef* uarthandler)
{
#if BOARD_UARTn > 0
	if (uarthandler == &uart1handler) {
#if (BOARD_SBUS_UART == 1) || (BOARD_DSM2_UART == 1)
		uint8_t i;
		for (i = 0; i < RC_FRAME_LEN; i++) {
			/* TODO dsm_parse_char */
			if (SBUS_FRAME_OK == sbus_parse_char(rc_dma_buf[i],
							     rc_channels)) {
				break;
			}
		}
		HAL_UART_Receive_DMA(&uart1handler, rc_dma_buf, RC_FRAME_LEN);
#endif
	}
#endif
#if BOARD_UARTn > 1
	else if (uarthandler == &uart2handler) {
#if (BOARD_SBUS_UART == 2) || (BOARD_DSM2_UART == 2)
		uint8_t i;
		for (i = 0; i < RC_FRAME_LEN; i++) {
			if (SBUS_FRAME_OK == sbus_parse_char(rc_dma_buf[i],
							     rc_channels)) {
				break;
			}
		}
		HAL_UART_Receive_DMA(&uart2handler, rc_dma_buf, RC_FRAME_LEN);
#endif
	}
#endif
}

/* overwrite 
 * http://stm32f4-discovery.com/2014/10/use-printf-output-stream-stm32f4/
 * */

/*
 * read
 * Read a character to a file. `libc' subroutines will use this system routine for input from all files, including stdin
 * Returns -1 on error or blocks until the number of characters have been read.
 * */
int _read(int file, char *ptr, int len)
{
	return 0;
}

/*
 * write
 * Write a character to a file. `libc' subroutines will use this system routine for output to all files, including stdout
 * Returns -1 on error or number of bytes sent
 * */
int _write(int file, char *ptr, int len)
{
#ifdef BOARD_STDOUT_UART
	board_uart_send(BOARD_STDOUT_UART - 1, (uint8_t *)ptr, len);
#endif
	return len;
}
